<template>
    <div>
        <Breadcrumb :route="route.matched" />
    </div>
    <div class="wb-container">
        <div class="mian-content">
            <div class="page-sub-toolbar" ref="SearchRef">
                <el-button type="primary" @click="AddGoods">添加商品</el-button>
                <el-button type="primary" @click="setRemovePeel">设置去皮重量</el-button>
                <el-button type="primary" @click=" dialogVisible = true">设置矫正砝码重量</el-button>
                <el-button type="primary" @click="correctWeightDr" :disabled="calibrationDisabled">发起校准</el-button>
            </div>
            <el-dialog v-model="dialogVisible" title="设置砝码重量" :header-cell-style="{ background: '#44abf7', color: '#fff' }"
                width="40%">
                <el-input placeholder="请输入砝码重量" v-model="weights"></el-input>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="ConfirmWeight">
                            确认
                        </el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 表单 -->
            <div class="form-box" :style="{ 'height': `calc(100vh - ${mianContentHeight + 180}px)` }">
                <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="demo-ruleForm"
                    :size="formSize" status-icon>
                    <el-form-item label="售卖价格：" prop="show_price">
                        <el-input v-model="form.show_price" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="预估总重量：" prop="all_weight">
                        <el-input v-model="form.all_weight" autocomplete="off" :disabled="disabled" />
                    </el-form-item>
                    <el-form-item label="商品重量：" prop="goods_weight" v-if="show">
                        <el-input v-model="form.goods_weight" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="销售数量：" prop="sales_num" v-if="show">
                        <el-input v-model="form.sales_num" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="波动值：" prop="f_value">
                        <el-input v-model="form.f_value" autocomplete="off" />
                    </el-form-item>
                    <el-form-item>
                        <div class="dialog-footer">
                            <el-button @click="goDeviceList">返回列表</el-button>
                            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                            <el-button type="primary" @click="submitForm()">
                                提交
                            </el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <el-dialog v-model="dialogTableVisible" title="选择要添加的商品"
            :header-cell-style="{ background: '#44abf7', color: '#fff' }" width="60%">
            <div class="searchGoods">
                <div>请输入要添加的商品名称：</div>
                <el-input type="text" placeholder="输入商品名称" v-model="saerchVal"></el-input>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </div>
            <el-table :data="list.data"
                :header-cell-style="{ background: '#CDD0D6', color: '#fff', fontSize: '14px', height: '40px', letterSpacing: '2px' }"
                style="width: 100%;height: 350px;" size="small" border>
                <template #empty>
                    <el-empty description="暂无数据！" />
                </template>
                <el-table-column prop="name" label="商品名称" min-width="100" align="center" fixed />
                <el-table-column prop="unit" label="单位" width="100" align="center" />
                <el-table-column prop="image" label="图片" width="100" align="center">
                    <template #default="scope">
                        <el-image :src="scope.row.image" style="height: 50px;" />
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" width="100" align="center" />
                <el-table-column prop="cost_price" label="成本价" width="100" align="center" />
                <el-table-column prop="type" label="商品类型" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag v-if="row.type == 1">称重商品</el-tag>
                        <el-tag v-if="row.type == 2">视觉商品</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="weight" label="商品重量" width="100" align="center" />
                <el-table-column prop="stock" label="库存" width="100" align="center" />
                <el-table-column prop="stock" label="操作" min-width="100" align="center" fixed="right">
                    <template #default="{ row }">
                        <div class="btn-stock">
                            <el-button type="primary" class="btn-radius" @click="addDeviceGoods(row)">选择商品</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div class="demo-pagination-block">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
                    :small="small" :disabled="disabled2" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-dialog>
    </div>
</template>
<script setup>
import { ElForm, ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref, watch, onMounted } from 'vue'
import { goodsList } from '@/api/goods'
import { DeviceGoodsEdit, setPeel, setWeight, WeightDo } from '@/api/Device'
import { useRouter, useRoute } from 'vue-router'
import Breadcrumb from "@/components/nav-header";

const route = useRoute()
const router = useRouter()
const formSize = ref('default')
const ruleFormRef = ref()
const show = ref(false)
const disabled = ref(false)
const saerchVal = ref('')
const SearchRef = ref()
const mianContentHeight = ref(0)
const list = reactive({
    data: [],
    goodsData: [],
    searchForm: {
        limit: 5,
        page: 1,
        name: ''
    }
})
const form = reactive({
    show_price: 0,
    all_weight: 0,
    goods_weight: 0,
    goods_id: 0,
    sales_num: 0,
    gross_weight: 0,
    f_value: 0
})
const dialogVisible = ref(false)
//砝码的重量
const weights = ref()
const calibrationDisabled = ref(true)
const correctWeightDialogVisible = ref(false)
//分页器数据
const currentPage = ref(1)
const pageSize = ref(5)
const small = ref(true)
const background = ref(true)
const disabled2 = ref(false)
const total = ref(0)
const rules = reactive({
    show_price: [
        { required: true, message: '此项必须填写', trigger: 'blur' },
    ],
    all_weight: [
        { required: true, message: '此项必须填写', trigger: 'blur' },
    ],
    goods_weight: [
        { required: true, message: '此项必须填写', trigger: 'blur' },
    ],
    sales_num: [
        { required: true, message: '此项必须填写', trigger: 'blur' },
    ],
    gross_weight: [
        { required: true, message: '此项必须填写', trigger: 'blur' },
    ],
    f_value: [
        { required: true, message: '此项必须填写', trigger: 'blur' },
    ]
})
//添加商品
const dialogTableVisible = ref(false)
watch(saerchVal, (old) => {
    if (old === '') {
        getGoodsList()
    }
})
onMounted(() => {
    mianContentHeight.value = SearchRef.value.clientHeight
})
//获取商品列表
const getGoodsList = async () => {
    list.searchForm.name = saerchVal.value
    const goodsData = await goodsList(list.searchForm).then(res => {
        const { code, data } = res
        if (code == 200) {
            list.data = data.data
            total.value = data.total
        }
    })
}
//分页
const handleSizeChange = (val) => {
    pageSize.value = val
    list.searchForm.limit = pageSize.value
    getGoodsList()
}
const handleCurrentChange = (value) => {
    currentPage.value = value
    list.searchForm.page = currentPage.value
    getGoodsList()
}
const handleSearch = () => {
    getGoodsList()
}

const AddGoods = () => {
    dialogTableVisible.value = true
    getGoodsList()
}

const addDeviceGoods = (res) => {
    form.show_price = res.price
    form.goods_weight = res.weight
    form.goods_id = res.id
    form.sales_num = res.sales
    if (res.sales_type == 1) {
        show.value = true
        disabled.value = true
        watch(
            () => form.goods_weight * form.sales_num,
            (sum) => {
                form.all_weight = sum
            }
        )
    } else if (res.sales_type == 2) {
        show.value = false
        disabled.value = false
    }
    dialogTableVisible.value = false
}

//表单的提交与取消
const resetForm = (Elform) => {
    if (!Elform) return
    Elform.resetFields()
}

const historyParam = history.state
const submitForm = async () => {
    let id = historyParam.editId
    form.lock_no = historyParam.lockId
    form.number = historyParam.num
    const edit = await DeviceGoodsEdit(id, form).then(result => {
        const { code, data } = result
        if (code == 200) {
            ElMessage.success('编辑成功')
            ruleFormRef.value.resetFields()
        }
    })
}
const setRemovePeel = () => {
    ElMessageBox.confirm(
        '请拿出框中所有的商品，再进行去皮操作',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const peel = await setPeel({
                device_id: historyParam.deviceId,
                lock_no: historyParam.lockId,
                inside_no: historyParam.num
            }).then(resp => {
                const { code, data } = resp
                if (code == 200) {
                    ElMessage.success('设置去皮成功')
                }
            })
        })
        .catch(() => {
        })

}

const ConfirmWeight = async () => {
    let weight_a = weights.value
    const weight = await setWeight({
        device_id: historyParam.deviceId,
        lock_no: historyParam.lockId,
        inside_no: historyParam.num,
        weight: weight_a
    }).then(e => {
        const { code, data } = e
        if (code == 200) {
            ElMessage.success('矫正砝码成功')
            dialogVisible.value = false
            calibrationDisabled.value = false
        }
    })
}

const correctWeightDr = async () => {
    const Weight = await WeightDo({
        device_id: historyParam.deviceId,
        lock_no: historyParam.lockId,
        inside_no: historyParam.num,
        weight: weights.value
    }).then(n => {
        const { code, data } = n
        if (code == 200) {
            ElMessage.success('校准成功')
            correctWeightDialogVisible.value = false
        }
    })
}

//返回门锁列表页
const goDeviceList = () => {
    router.go(-1)
}
</script>
<style lang="less" scoped>
.page-sub-toolbar {
    width: 100%;
    padding: 10px 0 15px 10px;
    border-bottom: 1px solid #efefef;
}

.btn {
    outline: none !important;
    padding: 8px 16px;
    border-radius: 2px;
    font-size: 12px;
    line-height: 1;
    color: #fff;
    text-align: center;
    vertical-align: middle;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    cursor: pointer;
    -webkit-transition: background-color 0.3s;
    -moz-transition: background-color 0.3s;
    transition: background-color 0.3s;
    border: 1px solid transparent;
}

.btn-sm {
    display: inline-block;
    padding: 7px 8px;
    border-radius: 2px;
    font-size: 12px;
    line-height: 1;
    color: #fff;
    background: #dddddd;
    text-align: center;
    vertical-align: middle;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    cursor: pointer;
    -webkit-transition: background-color 0.3s;
    -moz-transition: background-color 0.3s;
    transition: background-color 0.3s;
}

.btn-primary {
    background: #44abf7 !important;
    border-color: #44abf7 !important;
    color: #fff !important;
}

:deep(.typresStyle .el-form-item__content) {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.form-input {
    margin-top: 15px;
}

.video {
    display: flex;
}

.help-block {
    display: block;
    margin-top: 5px;
    margin-bottom: 10px;
    color: #737373;
}

.form-box {
    padding: 20px 30px;
}

.dialog-btn {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 20px;
}

:deep(.el-dialog) {
    header {
        background: rgb(68, 171, 247);
        margin-right: 0;

        .el-dialog__title {
            color: #fff;
        }

        .el-dialog__headerbtn i {
            color: #fff;
        }
    }
}

:deep(.el-dialog__close) {
    color: #fff;
}

:deep(.el-button) {
    padding: 2px 6px;
    font-size: 12px;
}

.dialog-footer {
    .el-button {
        padding: 4px 16px;
        font-size: 14px;
        letter-spacing: 2px;
    }
}

.btn-stock {
    display: flex;
    justify-content: center;
    align-items: center;

    .el-button {
        padding: 4px 10px;
        font-size: 12px;
        letter-spacing: 2px;
    }
}

.searchGoods {
    display: flex;
    flex-direction: row;
    padding: 20px;
    justify-content: flex-end;
    align-items: center;

    .el-input {
        width: 200px;
    }

    .el-button {
        padding: 4px 10px;
        font-size: 12px;
        letter-spacing: 2px;
    }
}

.page-sub-toolbar {
    .el-button {
        letter-spacing: 2px;
    }
}
</style>